<?php

require_once 'Zend/View/Helper/Abstract.php';


function modulo($n,$b) {
	return $n-$b*floor($n/$b);
}

//TODO: don't use Zend namespace, use our own
class Zend_View_Helper_RelTimeString extends Zend_View_Helper_Abstract
{
    public function relTimeString($timeSecond, $absolute = true, $utc = true)
    {
		if ($absolute === true) {
			if ($utc === true) {
				$difftime = time() - date('Z') - intval($timeSecond);
			} else {
				$difftime = time() - intval($timeSecond);
			}
		} else {
			$difftime = $timeSecond;
		}
		if ($difftime < 0) {
			return 'sometime in the future';
		} else if ($difftime == 0) {
			return 'a while ago';
		} else if ($difftime == 1) {
			return 'a second ago';
		} else if ($difftime < 60) {
			return sprintf('%d seconds ago', $difftime);
		} else if ($difftime < 120) {
			$mod = intval(modulo($difftime, 60));
			if ($mod > 0) {
				return sprintf('a minute, %d seconds ago', $mod);
			}
			return 'a minute ago';
		} else if ($difftime < 3600) {
			$mod = intval(modulo($difftime, 60));
			if ($mod > 0) {
				return sprintf('%d minutes, %d seconds ago', floor($difftime / 60), $mod);
			}
			return sprintf('%d minutes ago', floor($difftime / 60));
		} else if ($difftime < 7200) {
			$mod = intval(modulo($difftime, 3600));
			if ($mod > 60) {
				return sprintf('an hour, %d minutes ago', floor($mod / 60));
			}
			return 'an hour ago';
		} else if ($difftime < 86400) {
			$mod = intval(modulo($difftime, 3600));
			if ($mod > 60) {
				return sprintf('%d hours, %d minutes ago', floor($difftime / 3600), floor($mod / 60));
			}
			return sprintf('%d hours ago', floor($difftime / 3600));
		} else if ($difftime < 172800) {
			$mod = intval(modulo($difftime, 86400));
			if ($mod > 3600) {
				return sprintf('a day, %d hours ago', floor($mod / 3600));
			}
			return 'yesterday';
		} else {
			$mod = intval(modulo($difftime, 86400));
			if ($mod > 3600) {
				return sprintf('%d days, %d hours ago', floor($difftime / 86400), floor($mod / 3600));
			}
			return sprintf('%d days ago', floor($difftime / 86400));
		}
    }
}
